<template>
  <view class="field-form-item field-upload">
    <u-form-item
      :label="label"
      :required="required"
      :prop="prop"
    >
      <!-- 非图片类型的只读状态 -->
      <view v-if="readOnly && !isImage">
        <view v-for="(file, index) in uploadWidget.fileList" :key="index">
          <view @click="downloadFile(file)" style="color: royalblue">{{ file.name || file.filename }}</view>
        </view>
      </view>
      <u-upload
        v-else
        ref="upload"
        :action="action"
        :file-list="uploadWidget.fileList"
        :max-count="uploadWidget.maxCount"
        :preview-full-image="isImage"
        :auto-upload="true"
        :custom-btn="true"
        :deletable="!disabled && !readOnly"
        name="uploadFile"
        width="160"
        height="160"
        :header="header"
        :formData="formData"
        :disabled="disabled"
        @on-success="onUploadSuccess"
        @on-error="onUploadError"
        @on-remove="onRemoveFile"
      >
        <template v-slot:addBtn>
          <view v-if="!isImage && !readOnly" class="slot-btn" hover-class="slot-btn__hover" hover-stay-time="150">
            <u-icon name="plus" size="24"></u-icon>上传文件
          </view>
          <view v-else-if="!readOnly" class="u-list-item u-add-wrap" hover-class="u-add-wrap__hover" hover-stay-time="150"
            width="160" height="160">
            <u-icon name="camera" class="u-add-btn" size="40"></u-icon>
          </view>
        </template>
      </u-upload>
    </u-form-item>
  </view>
</template>

<script>
import { UploadWidget } from '@/utils/widget.js';
import { uploadMixin } from '@/utils/mixins';

export default {
  name: 'fieldUpload',
  props: {
    label: {
      type: String
    },
    value: {
      type: String
    },
    action: {
      type: String
    },
    name: {
      type: String,
      default: 'uploadFile'
    },
    formData: {
      type: Object
    },
    header: {
      type: Object
    },
    maxCount: {
      type: Number,
      default: 1
    },
    prop: {
      type: String
    },
    required: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    readOnly: {
      type: Boolean,
      default: false
    },
    isImage: {
      type: Boolean,
      default: true
    },
    downloadParams: {
      type: Object
    }
  },
  mixins: [uploadMixin],
  data() {
    return {
      uploadWidget: new UploadWidget(this.maxCount)
    }
  },
  methods: {
    onUploadSuccess(data, index, fileList, name) {
      let file = fileList[index].file;
      if (file) {
        file.downloadUri = data.data.downloadUri;
        file.filename = data.data.filename;
        file.uploadPath = data.data.uploadPath;
        this.uploadWidget.fileList.push(file);
        this.uploadWidget.onFileChange(file, this.uploadWidget.fileList);
        this.onChange();
      } else {
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        });
      }
    },
    onRemoveFile(index, fileList) {
      const file = this.uploadWidget.fileList[index];
      this.uploadWidget.fileList.splice(index, 1);
      this.uploadWidget.onFileChange(file, this.uploadWidget.fileList);
      this.onChange();
    },
    onChange() {
      let value = this.fileListToJson(
        this.uploadWidget.fileList
      );
      this.$emit('input', value);
    },
    initFileList(downloadParams) {
      if (this.$refs.upload) this.$refs.upload.clear();
      if (this.value != null && this.value !== '') {
        this.uploadWidget.fileList = this.parseUploadData(this.value, downloadParams);
      } else {
        this.uploadWidget.fileList = [];
      }
    },
    onUploadError (e, file, fileList) {
      this.$message.error('文件上传失败');
    },
    downloadFile(file) {
      if (file && file.url) {
        uni.downloadFile({
          url: file.url,
          success: (res) => {
            // 下载成功提示
            uni.showToast({
              icon: 'success',
              title: '下载成功！'
            });
            const filePath = res.tempFilePath;
            uni.openDocument({
              filePath: filePath,
              success: (res) => {
                console.log('打开文档成功');
              },
              fail: (err) => {
                console.log('打开文档失败', err);
              }
            });
          },
        });
      }
    }
  },
  watch: {
    downloadParams: {
      handler(val) {
        this.$nextTick(() => {
          this.initFileList(val);
        });
      },
      immediate: true
    }
  }
}
</script>

<style scoped lang="scss">
	.u-list-item {
		display: flex;
		align-items: center;
		justify-content: center;
		background: rgb(244, 245, 246);
		width: 160rpx;
		height: 160rpx;
		margin-left: -6rpx;
	}

	.u-add-wrap {
		flex-direction: column;
		font-size: 26rpx;
	}

	.slot-btn {
		border: 1px solid $u-type-primary;
		padding: 6rpx 14rpx;
		font-size: 28rpx;
		color: $u-type-primary;
		border-radius: 4rpx;
	}
</style>
